<?php
declare (strict_types=1);
// +----------------------------------------------------------------------
// | 评论
// +----------------------------------------------------------------------

namespace app\course\controller;


use app\BaseController;
use app\common\model\Article;
use app\common\model\Comment;

class AdminCommentController extends BaseController
{
    public function index()
    {
        $param = $this->request->param();
        $field = $param['field'] ?? 'id';
        $order = $param['order'] ?? 'desc';
        $limit = $param['limit'] ?? 10;

        $where = [];
        if (isset($param['keyword'])) {
            $where[] = ['content', 'like', '%' . $param['keyword'] . '%'];
        }
        if (isset($param['forum_id'])) {
            $where[] = ['commentable_id', '=', $param['forum_id']];
            $where[] = ['commentable_type', '=', 'app\model\Forum'];
        }

        $list  = Comment::with(['user' => function ($query) {
            $query->field('id,nickname,avatar');
        }])
            ->where($where)
            ->order($field, $order)
            ->paginate($limit);
        return [
            'code'    => 0,
            'message' => 'success',
            'count'   => $list->total(),
            'data'    => $list->items()
        ];
    }

    /**
     * 显示创建资源表单页.
     *
     * @return string
     */
    public function create()
    {

    }

    /**
     * 保存新建的资源
     *
     * @return \think\Response
     */
    public function save()
    {
        $result = Article::create($this->request->param());
        if (!$result) {
            return $this->error('保存失败');
        }
        return $this->success('保存成功');
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return array
     */
    public function read($id)
    {
        return Comment::find($id);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return string
     */
    public function edit($id)
    {
        $comment = Comment::find($id);
        return $this->success('保存成功', $comment);
    }

    /**
     * 保存更新的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function update($id)
    {
        Comment::update($this->request->param(), ['id' => $id]);
        return $this->success('保存成功');
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $comment = Comment::find($id);
        Article::where('id', $comment->commentable_id)
            ->dec('comment')
            ->update();
        $result = $comment->delete();
        if (!$result) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }
}